package com.archgeek.java.udp.v3zk;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

/**
 * @author pizhihui
 * @date 2023-03-08 15:59
 */
public class QuorumPeer {


    public static void main(String[] args) throws IOException {


        DatagramSocket udpSocket;
        try {

            udpSocket = new DatagramSocket(new InetSocketAddress("127.0.0.1", 2889));

        } catch (Exception e) {
            throw e;
        }


        byte[] b = new byte[36];
        DatagramPacket packet = new DatagramPacket(b, b.length);
        ByteBuffer responseBuffer = ByteBuffer.wrap(b);


        while (true) {
            System.out.println("等待服务端接收的数据......");
            udpSocket.receive(packet);
            System.out.println("接收到了数据..................");

            System.out.println("收到数据了.....length=" + packet.getLength());

            responseBuffer.clear();
            int xid = responseBuffer.getInt();
            System.out.println("xid=" + xid);

            long myid = 1;
            long currentVoteId = 1;
            long currentVoteZxid = 1000;
            responseBuffer.putLong(myid);
            responseBuffer.putLong(currentVoteId);
            responseBuffer.putLong(currentVoteZxid);

            packet.setData(b);

            System.out.println("packet.length=" + packet.getLength());
            udpSocket.send(packet);
            packet.setLength(b.length);

            System.out.println("===========");
            responseBuffer.clear();
            System.out.println(responseBuffer.getInt());
            System.out.println(responseBuffer.getLong());
            System.out.println(responseBuffer.getLong());
            System.out.println(responseBuffer.getLong());


            // 手工退出
//            if (System.in.read() == 0) {
//                break;
//            }
        }

//        udpSocket.close();

    }


}
